#include <iostream>
#include <unistd.h>
#include <typeinfo>
#include <any>

#define  DE 12
#ifdef DE
class Any{
    private:
        class holder{
            public:
                virtual ~holder(){};
                //纯虚函数，子类必须重写
                virtual const std::type_info& type() = 0;
                virtual holder* clone() = 0;//子类重写提供拷贝的功能
                //这个拷贝是深拷贝
        };

        template<class T>
        class placeholder:public holder{
            public:
                placeholder(const T& a):_val(a){}
                virtual const std::type_info& type(){
                    return typeid(T);
                }
                virtual holder* clone(){//2025-4-28修改：如果和基类纯虚函数声明不一致就会成为抽象类，无法实例化
                    return new placeholder<T>(_val);
                }
                

            public:
                T _val;
        };
        holder* _content;
    public:
        Any():_content(nullptr){}
        template<class T>
        Any(const T& val):_content(new placeholder<T>(val)){}
        Any(const Any&other):_content(other._content?other._content->clone():nullptr){}
        ~Any() { delete _content; }
        template <class T>
        T *get() { return &((placeholder<T> *)_content)->_val; }
        Any& swap(Any &other) { //因为要交换指针，所以不能用const
            std::swap(other._content, _content);
            return *this;
        }
        Any& operator=(const Any &other) { 
            //为val构造一个临时的通用容器，然后与当前容器自身进行指针交换，临时对象释放的时候，原先保存的数据也就被释放
            Any temp(other);
            return swap(temp);
        }
        template<class T>
        Any& operator=(const T&val){
            Any temp(val);
            return swap(temp);
        }
}; 

#endif 

class Test{
    
};
void test()
{
    using namespace std;
    Any a(123);
    int *pa = a.get<int>();
    std::cout << *pa << std::endl;
    a = Any(321);
    std::cout << (*pa) << std::endl;
    // const std::type_info& a = typeid(int);
    // cout << 123 << endl;
    // cout << a.name();
}

int main()
{
    std::any a = 1;
    int *pa = std::any_cast<int>(&a);
    std::cout << *pa << std::endl;

    a = "eho_char";
    const char **pc = std::any_cast<const char*>(&a);//必须加const
    std::cout << **pc << std::endl;

    a = std::string("eho");
    std::string *pb = std::any_cast<std::string>(&a);
    std::cout << *pb << std::endl;
}